package de.kardass.jannobatch;

import java.util.ArrayList;
import java.util.List;

public abstract class BufferedItemWriterAdapter<T> implements ItemWriter<T> {
	
	public static final int UNLIMITED = -1;
	
	protected final List<T> buffer = new ArrayList<T>();
	
	protected final int capacity;

	public BufferedItemWriterAdapter() {
		this(UNLIMITED);
	}
	
	public BufferedItemWriterAdapter(int capacity) {
		super();
		this.capacity = capacity;
	}

	public abstract void process(List<T> items);

	public final void write(T item) {
		buffer.add(item);
		if (buffer.size() == capacity) {
			flushBuffer();
		}
	}

    public void onShutDown() {
		if (buffer.size() > 0) {
			flushBuffer();
		}
	}

	public void onStartUp() {
	}
	
	private void flushBuffer() {
		process(buffer);
		buffer.clear();
	}

	public int getCapacity() {
    	return capacity;
    }
	
}
